/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */
#include "GameSceneManager.h"

#include "GlobalVariables.h"

#include "LoginScene.h"
#include "CharacterSelectScene.h"
#include "ServerChangeScene.h"
#include "EnterGameScene.h"
#include "EnterWorldScene.h"
#include "GameWorldScene.h"

namespace PQClient
{
	GameSceneManager::GameSceneManager() :
	_activeSceneId(Scene_Unkown),_lastSceneId(Scene_Unkown)
	{
		for(int i=0;i<Scene_Count;++i){
			for(int j=0;j<Scene_Count;++j){
				transitionTable[i][j]=0;
			}
		}

		//means scene transition is ok
		transitionTable[Scene_Unkown][Scene_Login]=1;
		transitionTable[Scene_Login][Scene_ServerChange]=1;
		transitionTable[Scene_ServerChange][Scene_EnterGame]=1;

		//
		transitionTable[Scene_Login][Scene_EnterWorld]=1;
		transitionTable[Scene_EnterWorld][Scene_GameWorld]=1;
	}

	GameSceneManager::~GameSceneManager()
	{
	}

	void GameSceneManager::createScene(SceneId id)
	{
		switch(id){
			case Scene_Login:
				_scenes[id]=new LoginScene();
				break;
			case Scene_EnterGame:
				_scenes[id]=new EnterGameScene();
				break;
			case Scene_EnterWorld:
				_scenes[id]=new EnterWorldScene();
				break;

			case Scene_GameWorld:
				_scenes[id]=new GameWorldScene();
				break;
			case Scene_CharacterSelect:
				_scenes[id]=new CharacterSelectScene();
				break;
			case Scene_ServerChange:
				_scenes[id]=new ServerChangeScene();
				break;
			default:
				_scenes[id]=0;
				break;

		}
	}

	void GameSceneManager::init()
	{
		//load our scenes.
		for(int i=0;i<Scene_Count;++i){
			createScene((SceneId)i);
		}

		setActiveSceneId(Scene_Login);

	}

	void GameSceneManager::update(float deltaT)
	{
		//
		if(_activeSceneId!=_lastSceneId){
			if(_scenes[_activeSceneId]){
				//check whether the scene can be changed
				if(isSceneTransitionAllowed(_lastSceneId,_activeSceneId)){
					_scenes[_activeSceneId]->activate();
					
					_lastSceneId=_activeSceneId;
				}

			}
			
			
		}

		_scenes[_activeSceneId]->update(deltaT);
	}

	bool GameSceneManager::isSceneTransitionAllowed(SceneId from,SceneId to)
	{
		assert(legalSceneId(from));
		assert(legalSceneId(to));

		//we need a transition table
		int row=(int)from;
		int col=(int)to;
		int state=transitionTable[row][col];

		if(state==0){
			assert(!"GameSceneManager::isSceneTransitionAllowed");
			return false;
		}
		
		return true;
	}

	bool GameSceneManager::legalSceneId(SceneId id)
	{
		if(id>=Scene_Unkown&&id<Scene_Count){
			return true;
		}
		return false;
	}


	void GameSceneManager::setActiveSceneId(SceneId id)
	{
		_activeSceneId=id;

	}

}
